import { uuid } from '../utils/uuid';
import { bcrypt } from '../utils/crypto';
import { userRepository, UserEntity } from '../utils/repository';
import { Service } from 'typedi';

@Service()
export class UserService {
  async login(entity: UserEntity) {
    let result = null;
    const record = await userRepository.findOneBy({ username: entity.username });
    if (record && bcrypt.compare(entity.password, record.password)) {
      result = record;
    }
    return result;
  }

  async register(entity: UserEntity) {
    const record = await userRepository.findOneBy({ username: entity.username });
    if (record) return -1;
    entity.uid = uuid.simpleUUID();
    entity.password = bcrypt.hash(entity.password);
    const { raw } = await userRepository.insert(entity);
    return raw.affectedRows;
  }

  async update(id: string, entity: UserEntity) {
    const record = await userRepository.findOneBy({ uid: id });
    if (!record) return -1;
    entity.password = bcrypt.hash(entity.password);
    const { affected } = await userRepository.update({ uid: id }, entity);
    return affected;
  }

  async select(id?: string) {
    if (id) {
      return await userRepository.findOneBy({ uid: id });
    }
    return await userRepository.find();
  }

  async findById(id: string) {
    return await userRepository.findOneBy({ uid: id });
  }

  async findByName(name: string) {
    return await userRepository.findOneBy({ username: name });
  }
}
